package com.digital.herbarium.service;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.digital.herbarium.Entity.Popular;
import com.digital.herbarium.Exception.CustomException;
import com.digital.herbarium.Mapper.PopularMapper;
import com.digital.herbarium.Util.TimeUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PopularService {

    @Autowired
    PopularMapper popularMapper;

    public PageInfo<Popular> getPopularInfo(Popular popular, int pageSize, int pageNum){
        PageHelper.startPage(pageNum, pageSize);
        List<Popular> ilist = popularMapper.getPopularInfo(popular);
        PageInfo<Popular> pageInfo = new PageInfo<>(ilist);
        return  pageInfo;
    }


    public  void delPopular(String id){
        if(StrUtil.hasEmpty(id) || StrUtil.hasBlank(id)){
            throw  new CustomException(400,"缺少信息id");
        }
        String[] strArr = id.split(",");
        Long[] ids = Convert.toLongArray(strArr);
        popularMapper.delPopular(ids);
    }

    public  Integer addPopular(Popular popular){
        popular.setState(1);
        popular.setCreatetime(TimeUtil.getNow());
        popularMapper.addPopular(popular);
        return popular.getId();
    }

    public void editPopular(Popular popular){
        if(popular.getId() == null || popular.getId() == 0){
            throw  new CustomException(400,"缺少信息id");
        }
          popularMapper.editPopular(popular);
//        delPopular(popular.getId().toString());
//        addPopular(popular);
    }


    public void offPopular(String id,Integer state){
        if(StrUtil.hasEmpty(id) || StrUtil.hasBlank(id)){
            throw  new CustomException(400,"缺少信息id");
        }
        if(state == 1){
            popularMapper.onPopular(Long.parseLong(id));
        }else if(state == -1){
            popularMapper.offPopular(Long.parseLong(id));
        }

    }

    public Integer getTotal(){
        return popularMapper.getTotal(null);
    }


    public Integer getYesterdayTotal(){
        String yesterday = TimeUtil.getYesterday();
        return popularMapper.getTotal(yesterday);
    }

    public Integer getNowTotal(){
        String now = TimeUtil.getNow();
        return popularMapper.getTotal(now);
    }

}
